import asyncio, time


async def say_after(delay, msg):
    await asyncio.sleep(delay)  # 非阻塞
    print(msg)


async def main():
    # t0 = time.perf_counter()
    # # 顺序执行，总耗时 2 s
    # await say_after(1, 'hello')
    # await say_after(1, 'world')
    # await say_after(1, '你')
    # await say_after(1, '好')
    # print('sequential:', time.perf_counter() - t0)
    t0 = time.perf_counter()
    # 创建任务列表
    tasks = [
        asyncio.create_task(say_after(1, 'hello')),
        asyncio.create_task(say_after(1, 'world')),
        asyncio.create_task(say_after(1, '你')),
        asyncio.create_task(say_after(1, '好')),
        asyncio.create_task(say_after(1, '大')),
        asyncio.create_task(say_after(1, '家')),
        asyncio.create_task(say_after(1, '好')),
        asyncio.create_task(say_after(1, '！'))
    ]
    #     并发处理耗时
    await asyncio.gather(*tasks)
    print('sequential:', time.perf_counter() - t0)


asyncio.run(main())
